#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <getch.h>

char role = '#';
char board[15][15];
int key_x = 7 , key_y = 7 , sock;
struct sockaddr_in dest_addr;
socklen_t addrlen = sizeof(dest_addr);

typedef struct sockaddr* SAP;

int init_gobang(const char* ip,short port)
{
	// 初始化网络
	sock = socket(AF_INET,SOCK_DGRAM,0);
	if(0 > sock)
	{
		perror("socket");
		return EXIT_FAILURE;
	}

	dest_addr.sin_family = AF_INET;
	dest_addr.sin_port = htons(port);
	dest_addr.sin_addr.s_addr = inet_addr(ip);

	// 初始化棋盘
	for(int x=0; x<15; x++)
	{
		for(int y=0; y<15; y++)
		{
			board[x][y] = '*';
		}
	}

	return sock;
}

void show_board(void)
{
	system("clear");
	for(int x=0; x<15; x++)
	{
		for(int y=0; y<15; y++)
		{
			printf(" %c",board[x][y]);
		}
		printf("\n");
	}
}

void get_key(void)
{
	char buf[256];
	if(role == '@')
	{
		printf("等待对方落子...\n");
		int ret = recvfrom(sock,buf,sizeof(buf),0,(SAP)&dest_addr,&addrlen);
		if(0 >= ret)
		{
			printf("对方逃跑了，恭喜你胜利了！\n");
			exit(EXIT_SUCCESS);
		}

		sscanf(buf,"%d %d",&key_x,&key_y);
		board[key_x][key_y] = '@';
	}
	else
	{
		printf("请你落子...\n");
		for(;;)
		{
			printf("\33[%d;%dH",key_x+1,(key_y+1)*2);
			switch(getch())
			{
			case 183: key_x>0 && key_x--; break;
			case 184: key_x<14 && key_x++; break;
			case 185: key_y<14 && key_y++; break;
			case 186: key_y>0 && key_y--; break;
			case 10:if('*' == board[key_x][key_y])
				{
					board[key_x][key_y] = '#';
					sprintf(buf,"%d %d",key_x,key_y);
					int ret = sendto(sock,buf,strlen(buf)+1,0,(SAP)&dest_addr,addrlen);
					if(0 >= ret)
					{
						printf("你掉线了！\n");
						exit(EXIT_FAILURE);
					}
					return;
				}
			}
		}
	}
}

int count_key(int off_x,int off_y)
{
	int count = 0;
	for(int x=key_x+off_x,y=key_y+off_y; 0<=x && x<15 && 0<=y && y<15 && board[x][y] == board[key_x][key_y]; x+=off_x,y+=off_y)
	{
		count++;
	}
	return count;
}

bool check_board(void)
{
	if(count_key(-1,0)+count_key(+1,0) >= 4)
		return true;
	if(count_key(0,-1)+count_key(0,+1) >= 4)
		return true;
	if(count_key(-1,-1)+count_key(+1,+1) >= 4)
		return true;
	if(count_key(-1,+1)+count_key(+1,-1) >= 4)
		return true;

	return false;
}

int main(int argc,char* const argv[])
{
	if(3 != argc)
	{
		printf("User：gobang ip port\n");
		return EXIT_SUCCESS;
	}

	if(0 > init_gobang(argv[1],atoi(argv[2])))
	{
		printf("初始化网络错误！\n");
		return EXIT_FAILURE;
	}

	for(;;)
	{
		// 显示棋盘
		show_board();

		// 落子
		get_key();

		if(check_board())
		{
			show_board();
			printf("恭喜%c胜利，游戏结束！\n",role);
			return EXIT_SUCCESS;
		}

		// 切换角色
		role = role=='@'?'#':'@';
	}
}
